<template>
  <div>
    购物车
    <CheckedAll :checkedAll="checkedAll" @setCheckedAll="setCheckedAll"></CheckedAll>
    <List :list="list" @calc="calc" @delListById="delListById"></List>
    <TotalVue :totalNum="totalNum" :totalPrice="totalPrice"></TotalVue>
  </div>
</template>

<script>
import CheckedAll from "@/components/shoppingcar/CheckedAll.vue";
import List from "@/components/shoppingcar/List.vue";
import TotalVue from "../components/shoppingcar/Total.vue";
export default {
  data() {
    return {
      checkedAll: false, //全选的状态
      list: [
        {
          id: 1,
          goodsname: "商品一",
          goodsnum: 10,
          goodsprice: 100,
          checked: false,
        },
        {
          id: 2,
          goodsname: "商品二",
          goodsnum: 1,
          goodsprice: 200,
          checked: false,
        },
        {
          id: 3,
          goodsname: "商品三",
          goodsnum: 2,
          goodsprice: 300,
          checked: false,
        },
      ],
    };
  },
  methods:{
    calc(item,num){//item引用类型
        item.goodsnum  = item.goodsnum +num;
    },
    delListById(id){
      this.list = this.list.filter(item=>item.id!=id);
      //这里要注意  数组的方法 是否会影响原数组
    },
    setCheckedAll(flag){
      //this.checkedAll = flag;
      this.list.forEach(item=>item.checked=flag);
    }
    
  },
  watch:{
    list:{
      deep:true,
      handler(){
          this.checkedAll = this.list.length?this.list.every(item=>item.checked):false;

      }
    }

  },
  computed:{
    totalNum(){
      let  num = 0;
      let  checkedList = this.list.filter(item=>item.checked);
      if(checkedList.length){
        num  = checkedList.map(item=>item.goodsnum).reduce((a,b)=>a+b);
      }


      return  num;

    },
    totalPrice(){
      let  num = 0;
      let  checkedList = this.list.filter(item=>item.checked);
      if(checkedList.length){
        num  = checkedList.map(item=>item.goodsnum*item.goodsprice).reduce((a,b)=>a+b);
      }
      return  num;

    }

  },

  components: {
    CheckedAll,
    List,
    TotalVue,
  },
};
</script>

<style></style>
